package com.example.service.impl;
import java.time.LocalDateTime;


import com.example.common.ErrorCode;
import com.example.constant.AlgorithmConstant;
import com.example.constant.UserConstant;
import com.example.exception.BusinessException;
import com.example.model.po.User;
import com.example.mapper.UserMapper;
import com.example.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author LinHui
 * @since 2024-03-28
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;




    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        log.info("账户注册开始~");
        //账号不能小于4位
        if (userAccount == null || userAccount.length() < 4) {
            log.info("账户注册出现异常，账户账号为空或者长度小于4位~");
            // todo 修改为自定义异常
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号为空/账号长度不够");
        }

        //密码不能小于8位
        if (userPassword == null || userPassword.length() < 8) {
            log.info("账户注册出现异常，账户密码为空或者长度小于8位~");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码为空/密码长度不够");
        }

        //账号不能包括特殊字符
        String pattern = "^[a-zA-Z0-9_]+$";
        Matcher matcher = Pattern.compile(pattern).matcher(userAccount);
        if (!matcher.find()) {
            log.info("账户注册出现异常，账户账号出现特殊字符~");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号出现特殊字符");
        }

        //密码必须和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            log.info("账户注册出现异常，俩次密码输入不同~");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户输入的密码和校验密码不同");
        }

        //账号不能重复
        boolean exists = lambdaQuery().
                eq(User::getUserAccount, userAccount).
                exists();

        if (exists) {
            log.info("账户注册出现异常，数据库中已有该账户~");
            throw new BusinessException(ErrorCode.USER_EXISTE);
        }

        //对密码进行加密

        String alPassword = MD5Utils.encrypt(UserConstant.SALT + userPassword, AlgorithmConstant.MD5);


        User user = new User();
        user.setUsername(userAccount);
        user.setUserAccount(userAccount);
        user.setAvatarUrl("https://pic.imeitou.com/uploads/allimg/221012/8-221012092201.jpg");
        user.setGender(1);
        user.setUserPassword(alPassword);
        user.setUserStatus(0);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setIsDelete(0);
        // todo 用户身份，默认为0，普通用户
        user.setUserRole(0);



        //向数据库中插入数据
        boolean Result = save(user);
        //if (!Result) {
        //    throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号异常，账户密码为空或者长度小于8位~");
        //}
        log.info("id为{}的用户注册成功~", user.getId());
        return  user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        log.info("用户登录~");
        //账号不能小于4位
        if (userAccount == null || userAccount.length() < 4) {
            log.info("用户账号异常，账号为空或者长度小于4位");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号异常");
        }

        //密码不能小于8位
        if (userPassword == null || userPassword.length() < 8) {
            log.info("用户账号异常，账户密码为空或者长度小于8位~");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号异常，账户密码为空或者长度小于8位~");
        }

        //账号不能包括特殊字符
        String pattern = "^[a-zA-Z0-9_]+$";
        Matcher matcher = Pattern.compile(pattern).matcher(userAccount);
        if (!matcher.find()) {
            log.info("用户账号异常，账户账号出现特殊字符~");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号异常，账户账号出现特殊字符~");
        }



        //账号不能重复

        userPassword = MD5Utils.encrypt(UserConstant.SALT + userPassword, AlgorithmConstant.MD5);
        User user = lambdaQuery().
                eq(User::getUserAccount, userAccount).
                eq(User::getUserPassword, userPassword).
                one();

        if (user == null) {
            log.info("用户账号异常，用户密码错误~请检查账号和密码是否正确");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号异常，用户密码错误~请检查账号和密码是否正确");
        }



        //脱敏，隐藏敏感信息

        User safteUser = getSafteUser(user);

        //记录用户的登录状态
        HttpSession session = request.getSession();
        session.setAttribute(UserConstant.USER_LOGIN_STATE, safteUser);


        log.info("id为{}的用户登录成功~", user.getId());
        return  safteUser;
    }


    @Override
    public User getSafteUser(User orgUser) {

        if (orgUser == null) {
            return null;
        }

        User safetUser = new User();
        safetUser.setId(orgUser.getId());           //用户id
        safetUser.setUsername(orgUser.getUsername());   //用户姓名
        safetUser.setUserAccount(orgUser.getUserAccount());     //账号
        safetUser.setAvatarUrl(orgUser.getAvatarUrl());     //头像
        safetUser.setGender(0);     //性别
        //safetUser.setUserPassword("");
        safetUser.setPhone(orgUser.getPhone());     //电话
        safetUser.setEmail(orgUser.getEmail());     //邮箱
        safetUser.setUserStatus(0);     //用户状态，是否被封号
        safetUser.setCreateTime(orgUser.getCreateTime());       //创建时间
        safetUser.setUserRole(orgUser.getUserRole()    );       //用户权限/角色
        //safetUser.setUpdateTime(LocalDateTime.now());
        //safetUser.setIsDelete(0);
        return safetUser;
    }


}
